#include "SnippetSearch.hpp"

int SnippetSearch::SearchQuery(string query, SnippetList& snippets)
{
  Keywords keywords;
  
  split(keywords, query, is_any_of(" "));
  return InternalSearch(keywords, snippets);
}

Snippet* SnippetSearch::SearchId(string snippetId, SnippetList& snippets)
{
  foreach (Snippet* snippet, snippets) {
    if (snippet->m_snippetId == snippetId)
      return snippet;
  }
  return NULL;
}

int SnippetSearch::InternalSearch(Keywords& keywords, SnippetList& snippets)
{
  unsigned int initialCount = snippets.size();
  
  foreach (Snippet* snippet, snippets) {
    if (StringContainsAnyOf(snippet->m_description, keywords))
      snippets.push_back(snippet);
  }
  
  // erase original results
  snippets.erase(snippets.begin(), snippets.begin() + initialCount);
  return snippets.size();
}

bool SnippetSearch::StringContainsAnyOf(string haystack, Keywords& keywords)
{
  foreach (string keyword, keywords) {
    if (haystack.find(keyword) != string::npos)
      return true;
  }
  return false;
}